// 已修复以下问题：
// 1. incenseTimers 拼写错误（inscense -> incense）
// 2. 异步批量上香逻辑异常
// 3. 结构整体保持不变，仅做 bug 修复

const app = getApp<IAppOption>();

interface Comment {
  content: string;
  id: string;
  commenterOpenId: string;
}

interface UserItem {
  openid: string;
  avatarUrl: string;
  nickName: string;
  lastCheckinDate: string;
  incenseCount: number;
  commentList?: Comment[];
  comments: Comment[];
  deadDays: number;
  achievement: string;
}

Page({
  data: {
    list: [] as UserItem[],
    page: 1,
    pageSize: 10,
    hasMore: true,
    isLoading: false,
    commentIndex: null as number | null,
    commentText: '',
    showActionsIndex: null as number | null,
    keyboardHeight: 0,
    incenseTimers: {} as Record<string, NodeJS.Timeout | null>,
    incenseCounts: {} as Record<string, number>,
    pulling: false,
    totalUsers: 0,
    totalIncense: 0,
    banners: [
      {
        "desc": "今日语录：活着就是胜利",
        "img": "cloud://cloud1-9gvsip401a78055c.636c-cloud1-9gvsip401a78055c-1301401218/banners/image1.png",
        "_id": "1"
      }
    ],              // banner 列表
  },

  onLoad() {
    this.loadSummary();
    this.loadData();
    this.loadBanners();       // 加载 banner 图
  },

  onReady() {
    wx.onKeyboardHeightChange(this.handleKeyboardHeightChange);
  },

  onUnload() {
    wx.offKeyboardHeightChange(this.handleKeyboardHeightChange);
  },

  onReachBottom() {
    this.loadData();
  },

  handleKeyboardHeightChange(res: WechatMiniprogram.OnKeyboardHeightChangeCallbackResult) {
    const keyboardHeight = res.height || 0;
    const tabBarHeight = 50;
    this.setData({ keyboardHeight: keyboardHeight - tabBarHeight });
  },

  handlePageTouch() {
    this.setData({
      commentIndex: null,
      showActionsIndex: null,
      keyboardHeight: 0,
    });
  },

  onInputBlur() {
    this.setData({ keyboardHeight: 0 });
  },

  toggleActions(e: WechatMiniprogram.TouchEvent) {
    const index = e.currentTarget.dataset.index;
    const current = this.data.showActionsIndex;
    this.setData({ showActionsIndex: current === index ? null : index });
  },

  closeActions() {
    this.setData({ showActionsIndex: null });
  },

  handleShowCommentBox(e: WechatMiniprogram.TouchEvent) {
    const index = e.currentTarget.dataset.index;
    this.setData({
      commentIndex: index,
      commentText: '',
      showActionsIndex: null,
    });
  },

  onCommentInput(e: WechatMiniprogram.Input) {
    this.setData({ commentText: e.detail.value });
  },

  submitComment() {
    const { commentIndex, commentText, list } = this.data;
    if (commentIndex === null || !commentText.trim()) return;

    const user = list[commentIndex];
    const commenterOpenId = app.globalData?.userId || '';
    if (!commenterOpenId) {
      wx.showToast({ title: '请先登录', icon: 'none' });
      return;
    }

    wx.cloud.callFunction({
      name: 'eulogy_operate',
      data: {
        action: 'add',
        content: commentText,
        deadOpenId: user.openid,
        commenterOpenId,
      },
    }).then(() => {
      const newComment = { content: commentText, id: String(Date.now()), commenterOpenId };
      const newList = [...list];
      newList[commentIndex].comments.push(newComment);
      this.setData({
        list: newList,
        commentIndex: null,
        commentText: '',
        showActionsIndex: null,
        keyboardHeight: 0,
      });
    }).catch(err => {
      console.error('留言失败', err);
      wx.showToast({ title: '留言失败', icon: 'none' });
    });
  },

  calculateAchievement(incenseCount: number) {
    if (incenseCount >= 100) return '烈火传承者🔥';
    if (incenseCount >= 50) return '敬香达人🌸';
    if (incenseCount >= 10) return '初级香客🌿';
    return '无';
  },

  loadData(callback?: () => void) {
    if (this.data.isLoading || !this.data.hasMore) {
      callback?.();
      return;
    }

    this.setData({ isLoading: true });

    wx.cloud.callFunction({
      name: 'user_operate',
      data: {
        action: 'getDeadUsers',
        openid: 'dummy',
        page: this.data.page,
        pageSize: this.data.pageSize,
      },
    }).then(res => {
      const rawList = res.result?.deadUsers || [];
      const now = Date.now();

      const newList = rawList.map(user => {
        const lastCheckin = new Date(user.lastCheckinDate).getTime();
        const diffDays = Math.floor((now - lastCheckin) / (1000 * 60 * 60 * 24));
        const incenseCount = user.incenseCount || 0;
        return {
          ...user,
          deadDays: diffDays,
          comments: user.commentList || [],
          incenseCount,
          achievement: this.calculateAchievement(incenseCount),
        };
      });

      const mergedList = [...this.data.list, ...newList];
      this.setData({
        list: mergedList,
        page: this.data.page + 1,
        hasMore: newList.length >= this.data.pageSize,
        isLoading: false,
      });
      callback?.();
    }).catch(err => {
      console.error('获取数据失败', err);
      this.setData({ isLoading: false });
      callback?.();
    });
  },

  loadSummary() {
    wx.cloud.callFunction({
      name: 'user_operate',
      data: { action: 'getSummaryStats', openid: 'dummy' },
    }).then(res => {
      const { totalUsers = 0, totalIncense = 0 } = res.result || {};
      this.setData({ totalUsers, totalIncense });
    }).catch(err => {
      console.error('获取汇总数据失败', err);
    });
  },

  handleIncense(e: WechatMiniprogram.TouchEvent) {
    const index = e.currentTarget.dataset.index;
    const user = this.data.list[index];
    const openid = user.openid;

    const newList = [...this.data.list];
    newList[index].incenseCount = (newList[index].incenseCount || 0) + 1;
    newList[index].achievement = this.calculateAchievement(newList[index].incenseCount);
    this.setData({ list: newList });

    const incenseCounts = { ...this.data.incenseCounts };
    incenseCounts[openid] = (incenseCounts[openid] || 0) + 1;
    this.setData({ incenseCounts });

    const incenseTimers = { ...this.data.incenseTimers };
    if (incenseTimers[openid]) clearTimeout(incenseTimers[openid]!);
    incenseTimers[openid] = setTimeout(() => {
      this.sendIncenseBatch(openid);
    }, 5000);
    this.setData({ incenseTimers });
  },

  sendIncenseBatch(openid: string) {
    const incenseCounts = { ...this.data.incenseCounts };
    const count = incenseCounts[openid] || 0;
    if (count <= 0) return;

    wx.cloud.callFunction({
      name: 'user_operate',
      data: {
        action: 'incenseBatch',
        targetId: openid,
        count,
        openid,
      },
    }).then(() => {
      incenseCounts[openid] = 0;
      const incenseTimers = { ...this.data.incenseTimers };
      if (incenseTimers[openid]) clearTimeout(incenseTimers[openid]!);
      incenseTimers[openid] = null;
      this.setData({ incenseCounts, incenseTimers });
    }).catch(err => {
      console.error('批量上香失败', err);
    });
  },

  onLongPressComment(e: WechatMiniprogram.TouchEvent) {

    const userIndex = e.currentTarget.dataset.userIndex;
    const commentIndex = e.currentTarget.dataset.commentIndex;
    const commentId = e.currentTarget.dataset.commentId;

    const comment = this.data.list[userIndex].comments[commentIndex];
    const myOpenid = app.globalData?.userId || '';

    if (comment.commenterOpenId !== myOpenid) {
      wx.showToast({ title: '只能删除自己的留言', icon: 'none' });
      return;
    }

    wx.showActionSheet({
      itemList: ['删除留言'],
      success: (res) => {
        if (res.tapIndex === 0) {
          wx.cloud.callFunction({
            name: 'eulogy_operate',
            data: { action: 'delete', id: commentId },
          }).then(() => {
            const newList = [...this.data.list];
            newList[userIndex].comments.splice(commentIndex, 1);
            this.setData({ list: newList });
          }).catch(err => {
            console.error('删除失败', err);
          });
        }
      },
    });
  },

  onPullDownRefresh() {
    this.setData({ page: 1, list: [], hasMore: true }, () => {
      this.loadSummary();
      this.loadData(() => {
        wx.stopPullDownRefresh();
      });
    });
  },

  onPageScroll() {
    // 页面滚动时关闭 actions-popup
    if (this.data.showActionsIndex || this.data.showActionsIndex === 0) {
      this.setData({ showActionsIndex: null });
    }
  },

  
  loadBanners() {
    wx.cloud.callFunction({
      name: 'banner_operate',
      success: (res) => {
        console.log('banners:', res.result.data)
        this.setData({
          banners: res.result.data
        })
      },
      fail: (err) => {
        console.error(err)
      }
    })
  },
  
  



});